﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using P2PWeb.Models;
using P2PWeb.Common;
using Nectar.DAL.Common;
using System.Data.Objects.DataClasses;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.ComponentModel;



namespace P2PWeb.Controllers
{

       public class AgentInfoObject
        {
            public int ID { get; set; }

           [DisplayName("代理商名称")]
           [Required(ErrorMessage = "请输入代理商名称.")]
            public string Name { get; set; }

           [DisplayName("联系地址")]
           [Required(ErrorMessage = "请输入联系地址")]
           public string Address { get; set; }

           public string Url { get; set; }

           [DisplayName("是否删除")]
           public bool IsDel { get; set; }

           [DisplayName("分润比例")]
           [Required(ErrorMessage="请输入分润比例")]
           [RegularExpression("^[0-9]*$", ErrorMessage = "借款金额必须为数字")]
           public double Ratio { get; set; }
                      
           [DisplayName("代理商类型")]
           [Range(1, 4, ErrorMessage = "请选择代理商类型")]
           public Nullable<global::System.Int32> AgentType
           {
               get;
               set;
           }

           [DisplayName("添加时间")]
           public DateTime CreationTime { get; set; }

           [DisplayName("添加人")]
           public string CreationUser { get; set; }

           [DisplayName("修改时间")]
           public DateTime UpdateTime { get; set; }

           [DisplayName("修改人")]
           public string UpdateUser { get; set; }

           [DisplayName("修改人ID")]
           public int UpdateUserID { get; set; }

           [DisplayName("添加人ID")]
           public int CreationUserID { get; set; }

           public Agent GetAgent()
           {
               return new Agent() { 
                ID=this.ID,
                Name=this.Name,
                CreationTime=this.CreationTime,
                CreationUser=this.CreationUser,
                CreationUserID=this.CreationUserID,
                UpdateTime=this.UpdateTime,
                UpdateUser=this.UpdateUser,
                UpdateUserID=this.UpdateUserID,
                Address=this.Address,
                IsDel=this.IsDel,
                Url=this.Url,
                AgentType=this.AgentType.ToString(),
                Ratio=this.Ratio
               };
           }
        }
    
       public class AgentSelectInfo
       {
           public int PageIndex { get; set; }

           public static AgentSelectInfo Default = new AgentSelectInfo()
           {
               PageIndex = 1,
           };
       }

       public class AccountSearchInfo
       {
           public int PageIndex { get; set; }
           public static AccountSearchInfo Default = new AccountSearchInfo()
           {
               PageIndex = 1,
           };
       }


    [AccountAuthorize(AccountType.Admin, AccountType.LookThrough)]
    public class AgentController : BaseController
    {
        //
        // GET: /Agent/

        //初始化数据
        public ActionResult Index(AgentSelectInfo agentInfo )
        {
            if (agentInfo == null || agentInfo.PageIndex == 0)
                agentInfo = AgentSelectInfo.Default;
            using (var context = new Repository<P2PModelContainer>())
            {
                Pager<Agent> pager = new Pager<Agent>();
                pager.CurrentPageIndex = agentInfo.PageIndex;
                QueryParameter isDelParameter = new QueryParameter("isDel", false);
                QueryParameter[] pageParameters = pager.GetQueryParameters();
                pager.Items = context.GetListOf<Agent>(" o.IsDel=@isDel order by o.CreationTime desc Skip @Skip Limit @Limit",
                pageParameters.Union(new[] { isDelParameter }).ToArray());
                pager.TotialItemsCount = context.GetListOf<Campaign>(" o.IsDel=@isDel", new[] { isDelParameter }).Count;
                var aa = pager.TotialPaqgerCount;
                if (Request.IsAjaxRequest())
                {
                    return PartialView("AgentInfoAjax", pager);
                }
                return View(pager);
            }
        }

        [AcceptVerbs("GET")]
        public ActionResult AgentInfo()
        {
                using (var context = new Repository<P2PModelContainer>())
                {
                    Account curAccount = context.GetEntityByID<Account>(CurrentUserInfo.ID);
                    if (curAccount.Status != (int)AccountState.Pass)
                    {
                        switch (curAccount.Status)
                        {
                            case (int)AccountState.New:
                                return new ContentResult()
                                {
                                    Content = "<script>alert('您还未通过实名认证,确定后填写实名信息');window.location='/account/AccountUploadify'</script>",
                                };
                            case (int)AccountState.LookThrough:
                                return new ContentResult()
                                {
                                    Content = "<script>alert('审核中，请稍后');window.location='/account/'</script>",
                                };
                            case (int)AccountState.Unfit:
                                return new ContentResult()
                                {
                                    Content = "<script>alert('实名认证失败,请重新审核');window.location='/account/AccountUploadify'</script>",
                                };
                            default:
                                break;
                        }
                    }
                }
                AgentInfoObject agn = null;
                using (var context = new Repository<P2PModelContainer>())
                {
                    agn = new AgentInfoObject()
                    {
                        AgentType = (int)Common.AgentType.common
                    };
                }                
                    return View(agn);                
        }

        [AcceptVerbs("Post")]
        [ValidateAntiForgeryToken]
        public ActionResult SaveAgentInfo(AgentInfoObject agentInfo)
        {
            if (ModelState.IsValid)
            {
                using (var context = new Repository<P2PModelContainer>())
                {
                    List<string> includes = new List<string>() { "AccountInfo", "AccountAuthentication" };
                    Account curAccount = context.GetEntityByID<Account>(CurrentUserInfo.ID, includes);
                    Agent agent = new Agent() {
                        Name = agentInfo.Name,
                        Url=agentInfo.Url,
                        AgentType=agentInfo.AgentType.ToString(),
                        CreationTime=DateTime.Now,
                        CreationUser=curAccount.Name,
                        CreationUserID=curAccount.ID,
                        IsDel=false,
                        Ratio=agentInfo.Ratio,
                        Address=agentInfo.Address
                    };
                   context.Add(agent);
                }
            }
            return RedirectToAction("Index", "Agent");
        }

        public ActionResult UpdateAgentInfo()
        {
            int id;
            int.TryParse(Request.QueryString["id"], out id);
            using (var context = new Repository<P2PModelContainer>())
            {
                Agent info = context.GetEntityByID<Agent>(id);
                ViewBag.Id = id;
                return View(info);
            }
        }

        public ActionResult UpdateAgent(Agent agent)
        {
            if (ModelState.IsValid)
            {
                using (var context = new Repository<P2PModelContainer>())
                {
                    Agent curAgent = context.GetEntityByID<Agent>(agent.ID);
                    curAgent.Name = agent.Name;
                    curAgent.Url = agent.Url;
                    curAgent.AgentType = agent.AgentType.ToString();
                    curAgent.UpdateUserID = CurrentUserInfo.ID;
                    curAgent.UpdateTime = DateTime.Now;
                    curAgent.UpdateUser = CurrentUserInfo.Name;
                    curAgent.Ratio = agent.Ratio;
                    curAgent.Address = agent.Address;
                    context.Update(agent);
                }
            }
            return RedirectToAction("Index", "Agent");
        }

        public ActionResult DeleteAgentInfo()
        {
            int id;
            int.TryParse(Request.QueryString["id"], out id);
            if(string.IsNullOrEmpty(id.ToString()))
            {
                return RedirectToAction("Index","Agent");
            }
            else
            {
                Agent ag = new Agent();
                ag.ID = id;
                  using (var context = new Repository<P2PModelContainer>())
                  {
                      context.Delete(ag);
                      return RedirectToAction("Index", "Agent");
                  }
            }
        }

        public ActionResult BindAgent(AccountSearchInfo accountInfo)
        {
            if (accountInfo == null || accountInfo.PageIndex == 0)
                accountInfo = AccountSearchInfo.Default;
            using (var context = new Repository<P2PModelContainer>())
            {
                Pager<Account> pager = new Pager<Account>();
                pager.CurrentPageIndex = accountInfo.PageIndex;
                QueryParameter isDelParameter = new QueryParameter("isDel", false);
                QueryParameter isDelParameter1 = new QueryParameter("isDel1", true);
                QueryParameter[] pageParameters = pager.GetQueryParameters();
                pager.Items = context.GetListOf<Account>(" o.IsDel = @isDel or o.IsDel = @isDel1  order by o.CreationTime desc Skip @Skip Limit @Limit",
                pageParameters.Union(new[] { isDelParameter, isDelParameter1 }).ToArray());
                pager.TotialItemsCount = context.GetListOf<Campaign>(" o.IsDel = @isDel or o.IsDel = @isDel1", new[] { isDelParameter, isDelParameter1 }).Count;
                var aa = pager.TotialPaqgerCount;
                if (Request.IsAjaxRequest())
                {
                    return PartialView("AccountListAjax", pager);
                }
                return View(pager);
            }
        }

        //启用禁用
        public ActionResult UpdateAccountIsDel()
        {
            int id;
            int.TryParse(Request.QueryString["id"], out id);
            if (string.IsNullOrEmpty(id.ToString()))
            {
                return RedirectToAction("BindAgent", "Agent");
            }
            else
            {
                using (var context = new Repository<P2PModelContainer>())
                {
                    Account curAccount = context.GetEntityByID<Account>(id);
                    if(curAccount.IsDel){
                        curAccount.IsDel = false;
                    }
                    else{
                        curAccount.IsDel = true;
                    }
                    curAccount.UpdateTime = DateTime.Now;
                    context.Update(curAccount);
                }
            }
            return RedirectToAction("BindAgent", "Agent");
        }

        public ActionResult AccountAndAgentList()
        {
            using (var context = new Repository<P2PModelContainer>())
            {
                int id;
                int.TryParse(Request.QueryString["id"], out id);
                List<Agent> list = new List<Agent>();
                Account curAccount = context.GetEntityByID<Account>(id);
                    Agent agent = new Agent();
                    QueryParameter[] isDelParameter = new QueryParameter[] { 
                    new QueryParameter("isDel", false)
                    };
                    List<Agent> Alllist = context.GetListOf<Agent>(" o.IsDel=@isDel order by o.CreationTime desc", isDelParameter);
                    if (Alllist != null && Alllist.Count > 0)
                    {
                        foreach (Agent ag in Alllist)
                        {
                            Agent agent_list = new Agent() { 
                             ID=ag.ID,
                             Name=ag.Name,
                             Ratio=ag.Ratio
                            };
                            list.Add(agent_list);  
                        }
                        ViewData["AgentList"] = list;
                    }
                    return View(curAccount);
              }
         }

        public ActionResult AccountAgentID()
        {
            int Account_Id;
            int.TryParse(Request.QueryString["Account_Id"], out Account_Id);
            int AgentId;
            int.TryParse(Request.QueryString["AgentId"], out AgentId);
            using (var context = new Repository<P2PModelContainer>())
            {
                Account curAccount = context.GetEntityByID<Account>(Account_Id);
                curAccount.AgentID = AgentId;
                curAccount.UpdateTime = DateTime.Now;
                curAccount.Type = 4;
                context.Update(curAccount);
            }
            return RedirectToAction("BindAgent", "Agent");
        }

    }
}
